#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node* next;
} Node;

// 创建新节点
Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    if (!newNode) {
        printf("内存分配失败\n");
        exit(EXIT_FAILURE);
    }
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// 在头部插入节点
Node* insertAtHead(Node* head, int data) {
    Node* newNode = createNode(data);
    newNode->next = head;
    return newNode;
}

// 在尾部插入节点
Node* insertAtTail(Node* head, int data) {
    Node* newNode = createNode(data);
    if (!head) return newNode;
    
    Node* current = head;
    while (current->next) current = current->next;
    current->next = newNode;
    return head;
}

// 删除指定值的第一个节点
Node* deleteNode(Node* head, int key) {
    Node* current = head;
    Node* prev = NULL;

    // 删除头节点的情况
    if (current && current->data == key) {
        head = current->next;
        free(current);
        return head;
    }

    while (current && current->data != key) {
        prev = current;
        current = current->next;
    }

    if (!current) return head;

    prev->next = current->next;
    free(current);
    return head;
}

// 查找节点
Node* findNode(Node* head, int key) {
    Node* current = head;
    while (current) {
        if (current->data == key) return current;
        current = current->next;
    }
    return NULL;
}

// 修改节点值
void updateNode(Node* node, int newValue) {
    if (node) node->data = newValue;
}

// 打印链表
void printList(Node* head) {
    Node* current = head;
    while (current) {
        printf("%d -> ", current->data);
        current = current->next;
    }
    printf("NULL\n");
}

// 释放链表内存
void freeList(Node* head) {
    Node* temp;
    while (head) {
        temp = head;
        head = head->next;
        free(temp);
    }
}

int main() {
    Node* head = NULL;

    head = insertAtHead(head, 10);
    head = insertAtTail(head, 20);
    head = insertAtHead(head, 5);

    printf("初始链表: ");
    printList(head);

    head = deleteNode(head, 10);
    printf("删除10后的链表: ");
    printList(head);

    Node* found = findNode(head, 20);
    if (found) printf("找到节点: %d\n", found->data);

    updateNode(found, 25);
    printf("更新后的链表: ");
    printList(head);

    freeList(head);
    return 0;
}    
